package com.das.mechanic_base.widget;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.das.mechanic_base.R;
import com.das.mechanic_base.adapter.alone.X3ShareAdapter;
import com.das.mechanic_base.app.X3Constent;
import com.das.mechanic_base.base.X3BaseActivity;
import com.das.mechanic_base.base.X3BaseSelfBottomSheetDialog;
import com.das.mechanic_base.bean.alone.AloneShareBean;
import com.das.mechanic_base.bean.ground.ShareWorkBean;
import com.das.mechanic_base.bean.task.AloneShareParamsBean;
import com.das.mechanic_base.mapi.api.NetWorkHttp;
import com.das.mechanic_base.mapi.response.HttpCallBack;
import com.das.mechanic_base.mapi.schedulers.RxSchedulersHelper;
import com.das.mechanic_base.utils.SpHelper;
import com.das.mechanic_base.utils.WxConfig;
import com.das.mechanic_base.utils.WxUtils;
import com.das.mechanic_base.utils.X3FileUtils;
import com.das.mechanic_base.utils.X3ScreenUtils;
import com.das.mechanic_base.utils.X3StringUtils;
import com.das.mechanic_base.utils.X3ToastUtils;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXMiniProgramObject;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * 施工底部操作按钮
 */
public class X3BottomShareWorkDialog extends X3BaseSelfBottomSheetDialog implements X3ShareAdapter.IOnItemClick {

    LinearLayout ll_share;
    X3BaseActivity mActivity;
    String picPath;

    public ShareWorkBean shareWorkBean;

    List<AloneShareBean> dataList;

    public X3BottomShareWorkDialog(@NonNull Context context, X3BaseActivity mActivity) {
        super(context, R.style.dialog2);
        this.mActivity = mActivity;

        //实现Dialog区域外部事件可以传给Activity
        //FLAG_NOT_TOUCH_MODAL作用：即使该window可获得焦点情况下，仍把该window之外的任何event发送到该window之后的其他window
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL,
                WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL);
        //FLAG_WATCH_OUTSIDE_TOUCH作用：如果点击事件发生在window之外，就会收到一个特殊的MotionEvent，为ACTION_OUTSIDE
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH,
                WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH);
    }

    @Override
    protected boolean getDialogCancel() {
        return false;
    }

    @Override
    protected void initView() {
        ll_share = getView(R.id.ll_share);
        dataList = initDataList();
        ll_share.removeAllViews();
        initIconLayout();
    }

    private void wxShare(){

        String wBId = "";
        if (shareWorkBean!=null){
            wBId = shareWorkBean.id+"";
        }
        String scene = "h=3&i="+ wBId  ;
        String path = "pages/report/index?" + scene;

        String appId = WxConfig.APP_ID; // 填移动应用(App)的 AppId，非小程序的 AppID
        IWXAPI api = WXAPIFactory.createWXAPI(mContext, appId,false);

        if (!WxUtils.isWeChatAppInstalled(mContext,api)){
            X3ToastUtils.showMessage(mContext.getString(R.string.work_share_wx));
            return;
        }

        WXMiniProgramObject miniProgramObj = new WXMiniProgramObject();
        miniProgramObj.webpageUrl = X3Constent.getShareMiniDefaultUrl(2) + wBId + "&timestamp=" + System.currentTimeMillis(); // 兼容低版本的网页链接
        if (X3Constent.isCnTest()){
            miniProgramObj.miniprogramType = WXMiniProgramObject.MINIPROGRAM_TYPE_PREVIEW;// 正式版:0，测试版:1，体验版:2
        } else {
            miniProgramObj.miniprogramType = WXMiniProgramObject.MINIPTOGRAM_TYPE_RELEASE;// 正式版:0，测试版:1，体验版:2
        }
        miniProgramObj.userName = WxConfig.MINI_ID;     // 小程序原始id
        miniProgramObj.path = path;            //小程序页面路径；对于小游戏，可以只传入 query 部分，来实现传参效果，如：传入 "?foo=bar"
        WXMediaMessage msg = new WXMediaMessage(miniProgramObj);
        String title = "";
        if (shareWorkBean!=null){
            title = shareWorkBean.carNum;
        }
        msg.title = title;                    // 小程序消息title
        msg.description = title;               // 小程序消息desc

        Bitmap bmp = BitmapFactory.decodeResource(mActivity.getResources(), R.mipmap.work_mini_cover);
        Bitmap thumbBmp = Bitmap.createScaledBitmap(bmp, 600, 478, true);
        bmp.recycle();
        msg.thumbData = WxUtils.bmpToByteArray(thumbBmp, true);// 小程序消息封面图片，小于128k

        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = buildTransaction("miniProgram");
        req.message = msg;
        req.scene = SendMessageToWX.Req.WXSceneSession;  // 目前只支持会话
        api.sendReq(req);

    }

    private String buildTransaction(final String type) {
        return (type == null) ? String.valueOf(System.currentTimeMillis()) : type + System.currentTimeMillis();
    }

    private void initIconLayout(){
        boolean isSdk = (boolean) SpHelper.getData(X3Constent.IS_OPEN_SDK, false);

        if (X3Constent.isChina() && !isSdk){

//            int gapH = X3ScreenUtils.dipToPx(27,mContext);
            LinearLayout.LayoutParams lp1 = new LinearLayout.LayoutParams(X3ScreenUtils.dipToPx(80,mContext),X3ScreenUtils.dipToPx(120,mContext));
            createIconViews(0,lp1,true);
            LinearLayout.LayoutParams lp2 = new LinearLayout.LayoutParams(X3ScreenUtils.dipToPx(80,mContext),X3ScreenUtils.dipToPx(120,mContext));
//            lp2.leftMargin = gapH;
            createIconViews(1,lp2,true);
            createIconViews(2,lp2,true);
            createIconViews(3,lp2,true);
            createIconViews(4,lp2,true);

        } else {

//            int holder = 54 * 4 + 20 * 2;
//            int gapH = (int) ((X3ScreenUtils.getScreenWidth(mContext) - X3ScreenUtils.dipToPx(holder,mContext)) / 3.0f);
            LinearLayout.LayoutParams lp1 = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,X3ScreenUtils.dipToPx(120,mContext));
            createIconViews(0,lp1,false);
            LinearLayout.LayoutParams lp2 = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,X3ScreenUtils.dipToPx(120,mContext));
//            lp2.leftMargin = gapH;
            createIconViews(1,lp2,false);
            createIconViews(2,lp2,false);
            createIconViews(3,lp2,false);

        }
    }

    private void createIconViews(int index,LinearLayout.LayoutParams lp,boolean isCn){
        AloneShareBean.ShareType type = dataList.get(index).type;
        LinearLayout ll = (LinearLayout) LayoutInflater.from(mContext).inflate(R.layout.x3_alone_share_item,null);
        ImageView iv = ll.findViewById(R.id.iv_img);
        TextView tv = ll.findViewById(R.id.tv_des);
        iv.setImageResource(dataList.get(index).picId);
        tv.setText(dataList.get(index).des);
        if(!isCn){
            lp.weight = 1;
        }
        ll.setLayoutParams(lp);
        ll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (type == AloneShareBean.ShareType.vx){
                    wxShare();
                }else if (type == AloneShareBean.ShareType.cover){
                    if (onItemClick!=null){
                        onItemClick.onItemClick(AloneShareBean.ShareType.cover);
                    }
                } else if (type == AloneShareBean.ShareType.msg){
                    X3AloneSendMsgDialog dialog = new X3AloneSendMsgDialog(mActivity);
                    if (shareWorkBean!=null){
                        dialog.carNum = shareWorkBean.carNum;
                    }
                    if (shareWorkBean !=null) {
                        dialog.setiBtnClick(new X3AloneSendMsgDialog.IBtnClick() {

                            @Override
                            public void iBtnAffirmClick(String mobile) {
                                try {
                                    long id = Long.parseLong(shareWorkBean.id);
                                    sendReport(mobile,id);
                                }catch (Exception e){
                                }
                            }
                        });
                    }

                    dialog.show();
                } else if (type == AloneShareBean.ShareType.url){
                    if (shareWorkBean !=null){
                        copy2Clipboard(shareWorkBean.reportUrl);
                    }
                } else if (type == AloneShareBean.ShareType.pic){
                    if (onItemClick!=null){
                        onItemClick.onItemClick(AloneShareBean.ShareType.pic);
                    }
                }
            }
        });
        ll_share.addView(ll);
    }

    private void sendReport(String mobile,long workBaseId){
        mActivity.showLoading("");
        NetWorkHttp.getApi().sendReport(mobile,workBaseId)
                .compose(RxSchedulersHelper.defaultComposeRequest())
                .subscribe(new HttpCallBack<Object>() {
                    @Override
                    protected void onDone(Object o) {
                        mActivity.hideLoading();
                        X3ToastUtils.showMessage(mActivity.getString(R.string.x3_send_live_success));
                        dismiss();
                    }

                    @Override
                    protected String LoadingMessage() {
                        return null;
                    }

                    @Override
                    protected void showError(String error) {
                        mActivity.hideLoading();
                    }
                });
    }

    private List<AloneShareBean> initDataList() {
        List<AloneShareBean> dataList = new ArrayList<>();

        boolean isSdk = (boolean) SpHelper.getData(X3Constent.IS_OPEN_SDK, false);

        if (X3Constent.isChina() && !isSdk){
            AloneShareBean aloneShareBean1 = new AloneShareBean();
            aloneShareBean1.type = AloneShareBean.ShareType.vx;
            aloneShareBean1.des = mContext.getString(R.string.x3_alone_share_vx);
            aloneShareBean1.picId = R.mipmap.x3_alone_share_vx;

            AloneShareBean aloneShareBean11 = new AloneShareBean();
            aloneShareBean11.type = AloneShareBean.ShareType.cover;
            aloneShareBean11.des = mContext.getString(R.string.select_page);
            aloneShareBean11.picId = R.mipmap.x3_alone_share_cover;

            AloneShareBean aloneShareBean2 = new AloneShareBean();
            aloneShareBean2.type = AloneShareBean.ShareType.msg;
            aloneShareBean2.des = mContext.getString(R.string.x3_alone_share_msg);
            aloneShareBean2.picId = R.mipmap.x3_alone_share_msg;

            AloneShareBean aloneShareBean3 = new AloneShareBean();
            aloneShareBean3.type = AloneShareBean.ShareType.url;
            aloneShareBean3.des = mContext.getString(R.string.x3_alone_share_url);
            aloneShareBean3.picId = R.mipmap.x3_alone_share_url;

            AloneShareBean aloneShareBean4 = new AloneShareBean();
            aloneShareBean4.type = AloneShareBean.ShareType.pic;
            aloneShareBean4.des = mContext.getString(R.string.x3_alone_share_pic);
            aloneShareBean4.picId = R.mipmap.x3_alone_share_pic;

            dataList.add(aloneShareBean1);
            dataList.add(aloneShareBean11);
            dataList.add(aloneShareBean2);
            dataList.add(aloneShareBean3);
            dataList.add(aloneShareBean4);

        } else {

            AloneShareBean aloneShareBean11 = new AloneShareBean();
            aloneShareBean11.type = AloneShareBean.ShareType.cover;
            aloneShareBean11.des = mContext.getString(R.string.select_page);
            aloneShareBean11.picId = R.mipmap.x3_alone_share_cover;

            AloneShareBean aloneShareBean2 = new AloneShareBean();
            aloneShareBean2.type = AloneShareBean.ShareType.msg;
            aloneShareBean2.des = mContext.getString(R.string.x3_alone_share_msg);
            aloneShareBean2.picId = R.mipmap.x3_alone_share_msg;

            AloneShareBean aloneShareBean3 = new AloneShareBean();
            aloneShareBean3.type = AloneShareBean.ShareType.url;
            aloneShareBean3.des = mContext.getString(R.string.x3_alone_share_url);
            aloneShareBean3.picId = R.mipmap.x3_alone_share_url;

            AloneShareBean aloneShareBean4 = new AloneShareBean();
            aloneShareBean4.type = AloneShareBean.ShareType.pic;
            aloneShareBean4.des = mContext.getString(R.string.x3_alone_share_pic);
            aloneShareBean4.picId = R.mipmap.x3_alone_share_pic;

            dataList.add(aloneShareBean11);
            dataList.add(aloneShareBean2);
            dataList.add(aloneShareBean3);
            dataList.add(aloneShareBean4);
        }

        return dataList;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.x3_alone_share_work_dialog;
    }

    @Override
    protected int getDialogHeight() {
        return X3ScreenUtils.dipToPx(140,mContext);
    }

    @Override
    public void dismiss() {
        super.dismiss();
        mActivity.finish();
    }

    @Override
    protected boolean getCanceledOnTouchOutside() {
        return false;
    }

    @Override
    protected boolean getControlCanceledOnTouchOutside() {
        return true;
    }

    @Override
    public void iOnItemCameraClick(int index, AloneShareBean.ShareType type) {
    }

    OnItemClick onItemClick;
    public void setOnItemClick(OnItemClick onItemClick){
        this.onItemClick = onItemClick;
    }
    public interface OnItemClick{
        void onItemClick(AloneShareBean.ShareType type);
    }

    private void copy2Clipboard(String content) {
        ClipboardManager clipboard = (ClipboardManager) this.getContext().getSystemService(Context.CLIPBOARD_SERVICE);
        //创建ClipData对象
        //第一个参数只是一个标记，随便传入。
        //第二个参数是要复制到剪贴版的内容
        ClipData clip = ClipData.newPlainText("content", content);
        //传入clipData对象.将文本内容放到系统剪贴板里。
        clipboard.setPrimaryClip(clip);
        String tip = "";
        tip = this.getContext().getString(R.string.x3_alone_share_copy);
        X3ToastUtils.showMessage(tip);
    }
}
